﻿/*
Come from
http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
*/

(function ($) {
    $.fn.drags = function (opt) {

        opt = $.extend({ handle: "", cursor: "move" }, opt);

        var $el = (opt.handle === "") ? this : this.find(opt.handle);

        return $el.css('cursor', opt.cursor)
			.on("mousedown", function (ev) {
			    var $drag = (opt.handle === "") ? $(this).addClass('draggable') : $(this).addClass('active-handle').parent().addClass('draggable');

			    var z_idx = $drag.css('z-index'),
					drg_h = $drag.outerHeight(),
					drg_w = $drag.outerWidth(),
					pos_y = $drag.offset().top + drg_h - ev.pageY,
					pos_x = $drag.offset().left + drg_w - ev.pageX;

			    $drag.css('z-index', 1000).parents().on("mousemove", function (e) {
			        $('.draggable').offset({
			            top: e.pageY + pos_y - drg_h,
			            left: e.pageX + pos_x - drg_w
			        }).on("mouseup", function () {
			            $(this).removeClass('draggable').css('z-index', z_idx);
			        });
			    });
			    ev.preventDefault(); // disable selection
                opt.dragStart && opt.dragStart($drag);
            })
			.on("mouseup", function (e) {
			    var _this = $(this);
			    var pos = _this.offset();
			    //var item = _this.detach();

			    var targetElement = $($.elementFromPoint(e.pageX, e.pageY));
			    //var offset = targetElement.offset();
			    //item.appendTo(targetElement);
			    //item.offset({ left: pos.left, top: pos.top });
			    //item.position(pos.left - offset.left, pos.top - offset.top);
			    if (opt.handle === "") {
			        _this.removeClass('draggable');
			    } else {
			        _this.removeClass('active-handle').parent().removeClass('draggable');
			    }
			    if (opt.dropBack) {
			        opt.dropBack(_this, pos, targetElement);
			    }

			});
    }
})(jQuery);

(function ($) {
    var check = false, isRelative = true;

    $.elementFromPoint = function (x, y) {
        if (!document.elementFromPoint) return null;

        if (!check) {
            var sl;
            if ((sl = $(document).scrollTop()) > 0) {
                isRelative = (document.elementFromPoint(0, sl + $(window).height() - 1) == null);
            }
            else if ((sl = $(document).scrollLeft()) > 0) {
                isRelative = (document.elementFromPoint(sl + $(window).width() - 1, 0) == null);
            }
            check = (sl > 0);
        }

        if (!isRelative) {
            x += $(document).scrollLeft();
            y += $(document).scrollTop();
        }

        return document.elementFromPoint(x, y);
    }

})(jQuery);